package rsa

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"os"
)

// GenerateKey 生成RSA密钥对， bits是证书长度
// 通过 x509 标准得到的序列化为 ASN.1 的 DER 编码字符串，然后进行pem格式编码
func GenerateKey(bits int) (private []byte, public []byte, err error) {
	key, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, nil, err
	}

	// 私钥
	x509PrivateKey := x509.MarshalPKCS1PrivateKey(key)
	priPem := pem.EncodeToMemory(&pem.Block{Type: "RSA Private Key", Bytes: x509PrivateKey})

	// 公密
	x509PublicKey, err := x509.MarshalPKIXPublicKey(key.Public())
	pubPem := pem.EncodeToMemory(&pem.Block{Type: "RSA Public Key", Bytes: x509PublicKey})

	return priPem, pubPem, err
}

// GenerateKeyToFile 生成RSA密钥对，并保存到文件
func GenerateKeyToFile(bits int, priFilename, pubFilename string) error {
	pri, pub, err := GenerateKey(bits)
	if err != nil {
		return err
	}

	if err := os.WriteFile(pubFilename, pub, 0644); err != nil {
		return err
	}
	return os.WriteFile(priFilename, pri, 0644)
}
